package com.ibangnuo.manage.service.employee;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ibangnuo.framework.domain.*;
import com.ibangnuo.framework.domain.request.employee.EmployeeRequest;
import com.ibangnuo.framework.domain.request.employee.SalesmanQueryRequest;
import com.ibangnuo.framework.model.response.CommonCode;
import com.ibangnuo.framework.model.response.QueryResponseResult;
import com.ibangnuo.framework.model.response.QueryResult;
import com.ibangnuo.framework.utils.MD5Utils;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;
import com.ibangnuo.manage.dao.*;
import com.ibangnuo.manage.dao.employee.*;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:ly
 * @Data:2019/12/27 11:28
 * @Verdion:1.0
 */
@Service
public class EmployeeService {

    private static Logger LOGGER = LoggerFactory.getLogger(EmployeeService.class);

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AgentRepository agentRepository;
    @Autowired
    private UserRoleRepository userRoleRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private CommercialRepository commercialRepository;
    @Autowired
    private CommercialMapper commercialMapper;
    @Autowired
    private OrderTotalRepository orderTotalRepository;
    @Autowired
    private OrderTotalMapper orderTotalMapper;

    /**
     * 分页条件查询员工信息
     *
     * @param employeeRequest
     * @return
     */
    @Transactional
    public QueryResponseResult query(EmployeeRequest employeeRequest) {
        LOGGER.info("员工查询的参数:{}", employeeRequest.toString());
        if (employeeRequest == null) {
            employeeRequest = new EmployeeRequest();
        }
        String page1 = employeeRequest.getPage();
        Integer page = Integer.parseInt(page1);
        String size1 = employeeRequest.getLimit();
        Integer size = Integer.parseInt(size1);
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 20;
        }
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        String loginUserId = user1.getId();
        //管理员登录查询
        if (user1.getType() == 0) {
            employeeRequest.setAgentId("");
            if (employeeRequest.getAdminIdAgentId() != null && employeeRequest.getAdminIdAgentId() != "") {
                Optional<Agent> byId = agentRepository.findById(employeeRequest.getAdminIdAgentId());
                if (byId.isPresent()) {
                    employeeRequest.setAdminIdAgentId(byId.get().getCompanyName());
                }
            } else {
                employeeRequest.setAdminIdAgentId("");
            }
        } else {
            //代理商登录查询
            Agent byUserId = agentRepository.findByUserId(loginUserId);
            String agentId = byUserId.getId();
            employeeRequest.setAgentId(agentId);
            employeeRequest.setAdminIdAgentId(byUserId.getCompanyName());
        }
        PageHelper.startPage(page, size);
        QueryResult queryResult = new QueryResult();
        List<Map> all = employeeMapper.queryBy(employeeRequest);
        for (Map map : all) {
            int adminSex = (int) map.get("adminSex");
            if (adminSex == 0) {
                map.put("adminSex", "男");
            } else {
                map.put("adminSex", "女");
            }
        }
        PageInfo<Map> pageInfo = new PageInfo<Map>(all);
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

    /**
     * 员工删除
     *
     * @param adminUuid
     * @return
     */
    @Transactional
    public QueryResponseResult delAdmin(String adminUuid) {
        LOGGER.info("删除员工的信息:{}", adminUuid);
        if (adminUuid != null && !"null".equals(adminUuid) && !"".equals(adminUuid)) {
            Optional<Employee> employees = employeeRepository.findById(adminUuid);
            Employee employee = employees.get();
            String userId = employee.getUserId();
            Optional<User> byId = userRepository.findById(userId);
            User user = byId.get();
            user.setIsDelete(0);
            userRepository.save(user);
            employee.setIsDelete(0);
            employeeRepository.save(employee);
//            userRepository.deleteById(userId);
//            employeeRepository.deleteById(adminUuid);
            return new QueryResponseResult(CommonCode.SUCCESS, null);
        }
        return new QueryResponseResult(CommonCode.FAIL, null);
    }

    /**
     * 员工添加
     * 1.添加user
     * 1.获取当前用户userid
     * 2.获取代理商id
     * 3.添加employee的真实姓名和代理商id
     *
     * @param employeeRequest
     * @return
     */
    @Transactional
    public QueryResponseResult addEmployees(EmployeeRequest employeeRequest) {
        LOGGER.info("添加员工的信息:{}", employeeRequest.toString());
        if (employeeRequest == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        String username = employeeRequest.getAdminUsername();
        User byUsername = userRepository.findByUsername(username);
        System.out.println(byUsername);
        if (byUsername != null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        User user = new User();
        user.setEmail(employeeRequest.getAdminEmail());
        user.setPhone(employeeRequest.getAdminPhone());
        user.setCreateTime(new Date());
        user.setIsDelete(1);
        String password = MD5Utils.md5(employeeRequest.getAdminPassword(), "wang");
        user.setPassword(password);
        long number = PrimaryKeyUtil.nextId();
        String number1 = Long.toString(number);
        user.setNumber(number1);
        user.setType(4);
        if (employeeRequest.getAdminSex().equals("男")) {
            user.setSex(0);
        } else {
            user.setSex(1);
        }
        user.setStatus(1);
        user.setUsername(employeeRequest.getAdminUsername());
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        String loginUserId = user1.getId();
        if (user1.getType() == 0) {
            //管理员添加员工到user
            String agentId = employeeRequest.getAdminIdAgentId();
            user.setAgentId(agentId);
        } else {
            //代理商添加员工
            user.setAgentId(loginUserId);
        }

        User save = userRepository.save(user);
        Employee employee = new Employee();
        if (user1.getType() == 0) {
            employee.setAgentId(employeeRequest.getAdminIdAgentId());
        } else {
            Agent byUserId = agentRepository.findByUserId(loginUserId);
            String agentId = byUserId.getId();
            employee.setAgentId(agentId);
        }
        employee.setName(employeeRequest.getAdminName());
        employee.setUserId(save.getId());
        employee.setIsDelete(1);
        employee.setCreateTime(new Date());
        Employee save1 = employeeRepository.save(employee);
        //添加关系表
        Role role = roleRepository.findByRoleCode("employee");
        String roleId = role.getId();
        UserRole userRole = new UserRole();
        userRole.setUserId(save.getId());
        userRole.setRoleId(roleId);
        userRole.setCreateTime(new Date());
        userRoleRepository.save(userRole);
        return new QueryResponseResult(CommonCode.SUCCESS, null);
    }

    /**
     * 员工信息回显
     *
     * @param id
     * @return
     */
    public QueryResponseResult findById(String id) {
        LOGGER.info("员工查询的参数:{}", id);
        if (id == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        QueryResult queryResult = new QueryResult();
        List<Map> all = employeeMapper.queryById(id);
        for (Map map : all) {
            int adminSex = (int) map.get("adminSex");
            if (adminSex == 0) {
                map.put("adminSex", "男");
            } else {
                map.put("adminSex", "女");
            }
        }
        if (all.size() > 0 && all != null) {
            queryResult.setList(all);
            queryResult.setTotal(all.size());
            return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        }
        return new QueryResponseResult(CommonCode.FAIL, null);
    }

    /**
     * 员工编辑
     * 先根据编号（员工id）来查询出员工的信息
     * 根据出userid查询出user信息
     * 将user和employee中信息替换为表单中的信息
     *
     * @param employeeRequest
     * @return
     */
    @Transactional
    public QueryResponseResult editEmployees(EmployeeRequest employeeRequest) {

        LOGGER.info("编辑员工的信息:{}", employeeRequest.toString());
        if (employeeRequest == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        String employeeId = employeeRequest.getAdminNumber();
        Optional<Employee> employees = employeeRepository.findById(employeeId);
        Employee employee = employees.get();
        employee.setName(employeeRequest.getAdminName());
        employeeRepository.save(employee);
        String userId = employee.getUserId();
        Optional<User> byId = userRepository.findById(userId);
        User user = byId.get();
        user.setEmail(employeeRequest.getAdminEmail());
        user.setPhone(employeeRequest.getAdminPhone());
        user.setCreateTime(employeeRequest.getAdminCreateTime());

        if (employeeRequest.getAdminPassword() != null) {
            String password = MD5Utils.md5(employeeRequest.getAdminPassword(), "wang");
            user.setPassword(password);
        }
        user.setUpdateTime(new Date());
        if (employeeRequest.getAdminSex().equals("男")) {
            user.setSex(0);
        } else {
            user.setSex(1);
        }
        user.setStatus(employeeRequest.getAdminState());
        user.setUsername(employeeRequest.getAdminUsername());
        userRepository.save(user);
        /*UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(employeeRequest.getRoleId());
        userRole.setCreateTime(new Date());
        userRoleRepository.save(userRole);*/
        return new QueryResponseResult(CommonCode.SUCCESS, null);
    }


    //业务员业绩查询
    public QueryResponseResult performanceEnquiry(SalesmanQueryRequest salesmanQueryRequest) {
        LOGGER.info("业务员业绩查询的参数:{}", salesmanQueryRequest.toString());
        String page1 = salesmanQueryRequest.getPage();
        Integer page = Integer.parseInt(page1);
        String size1 = salesmanQueryRequest.getSize();
        Integer size = Integer.parseInt(size1);
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 20;
        }
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        String userId = user1.getId();
        Agent byUserId = agentRepository.findByUserId(userId);
        QueryResult queryResult = new QueryResult();
        if (byUserId != null) {
            String agentId = byUserId.getId();
            salesmanQueryRequest.setAgentId(agentId);
            PageHelper.startPage(page, size);
            List<Map> list = commercialMapper.findByEmployee(salesmanQueryRequest);
            PageInfo<Map> pageInfo = new PageInfo<>(list);
            for (Map map : list) {
                String employeeId = (String) map.get("employeeId");
                Optional<Employee> byId = employeeRepository.findById(employeeId);
                if (byId.isPresent()) {
                    String employeeName = byId.get().getName();
                    map.put("employeeName", employeeName);
                }
            }
            queryResult.setList(pageInfo.getList());
            queryResult.setTotal(pageInfo.getTotal());
        }
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }


    //业务员流水
    public QueryResponseResult salemanWater(SalesmanQueryRequest salesmanQueryRequest) {
        LOGGER.info("业务员流水的参数:{}", salesmanQueryRequest.toString());
        String page1 = salesmanQueryRequest.getPage();
        Integer page = Integer.parseInt(page1);
        String size1 = salesmanQueryRequest.getSize();
        Integer size = Integer.parseInt(size1);
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 20;
        }
        Map<String, String> m = new HashMap<>();
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        String userId = user1.getId();
        Agent byUserId = agentRepository.findByUserId(userId);
        Date time = salesmanQueryRequest.getStartTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        if (time != null) {
            String startTime = sdf.format(time) + "-%";
            salesmanQueryRequest.setCreateTime(startTime);
            m.put("createTime", startTime);
        }

        QueryResult queryResult = new QueryResult();
        if (byUserId != null) {
            String agentId = byUserId.getId();
            salesmanQueryRequest.setAgentId(agentId);
            PageHelper.startPage(page, size);
            List<Map> list = employeeMapper.findEmployeeWater(salesmanQueryRequest);//员工


            PageInfo<Map> pageInfo = new PageInfo<Map>(list);
            for (Map map : list) {
                String employeeId = (String) map.get("employeeId");
                m.put("employeeId", employeeId);

                int commercialCount = commercialMapper.findByEmployeeId(m);//商户数量
                map.put("commercialCount", commercialCount);
                Map resultMap = orderTotalMapper.findSettleAccounts(m);
                String    settleAccount1 = (String ) resultMap.get("settleAccount");
                double settleAccount=0;
                if (settleAccount1!=null){
                    settleAccount=Double.parseDouble(settleAccount1);
                }
                long  settleCount = (Long) resultMap.get("settleCount");
                map.put("settleCount", settleCount);
                map.put("settleAccount", settleAccount);

            }
            Collections.sort(list, (m1,m2)->{
                return Integer.parseInt(m2.get("commercialCount")+"")-Integer.parseInt(m1.get("commercialCount")+"");
            });
            queryResult.setList(pageInfo.getList());
            queryResult.setTotal(pageInfo.getTotal());
        }
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

    /**
     * 查询当前代理商下的员工
     * @return
     */
    public QueryResponseResult findAllByAgentId(){
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user1.getId());
        List<Employee> employeeList = employeeRepository.findByAgentIdAndIsDelete(agent.getId(), 1);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(employeeList);
        queryResult.setTotal(employeeList.size());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }
}
